﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DXApplicationTangche.service;
using System.Drawing.Printing;
using DXApplicationTangche.report;
using DevExpress.Xpf.Printing;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using DXApplicationTangche.Utils;
using DiaoPaiDaYin;
using WindowsFormsApplication4.DTO;
using System.IO;
using static WindowsFormsApplication4.UC.Frm导航;
using DevExpress.XtraGrid.Demos.util;

namespace DXApplicationTangche.快递打印
{
    public partial class XtraForm运单打印 : DevExpress.XtraEditors.XtraForm
    {
        private SfExpressMessageResult sfExpressMessageResult;
        private orderReqContactInfo orderReqContactInfo;
        private String post_code;   //  邮编
        private String QR_OTHER10; //  订单号
        private String formarea;//目的地

        private 发货类型 @enum;
        List<快递打印信息DTO> 快递打印信息DTOs = new List<快递打印信息DTO>();

        public XtraForm运单打印(发货类型 @enum)
        {
            InitializeComponent();
            this.@enum = @enum;
            if (!Directory.Exists(@"pic"))
            {
                Directory.CreateDirectory(@"pic");
            }
        }

        private void textEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                DataRow dataRow = new 快递Service().get交易单号信息(this.textEdit1.Text);

                this.textBox交易单号.Text = dataRow["QR_NAME"].ToString();
                this.textBox姓名.Text = dataRow["QR_OTHER26"].ToString();
                this.textBox电话.Text = dataRow["QR_OTHER27"].ToString();
                this.textBox收货地址.Text = dataRow["Address"].ToString();
                //formarea = ;
                this.post_code = dataRow["QR_OTHER32"].ToString();
                this.QR_OTHER10 = dataRow["QR_OTHER10"].ToString();

                textBox6.Text = new 快递Service().waybillcode_get();
              

            }
        }

        /// <summary>
        /// 上传订单信息
        /// </summary>
        private 京配地址DTO uploadInfo()
        {
            new 快递Service().waybill_send(this.textEdit1.Text, this.textBox姓名.Text, this.textBox收货地址.Text, this.textBox电话.Text, this.post_code,this.textBox6.Text);
            return new 快递Service().range_check(this.textEdit1.Text, this.textBox收货地址.Text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //  上传快递信息
            京配地址DTO 京配地址DTO = this.uploadInfo();
            this.devReport打印(京配地址DTO);

            /*          
             * 姓名          
             * 运单号
             * 电话
             * 条码
             * 地址
             * 时间
             */
            //string Time =DateTime.Now.Millisecond.ToString();
            DateTime t = System.DateTime.Now;
            string Instersql = " insert into a_yundanxinxi\n" +
            "( name,waybill_number,phone,code,address,printingTime)\n" +
            "values ( '" + this.textBox姓名.Text + "','" + this.textBox6.Text + "','" + this.textBox电话.Text + "','" + this.QR_OTHER10 + "','" + this.textBox收货地址.Text + "','" + t.ToString()+ "')";

            SQLmtm.GetDataRow(Instersql);
           
            return;
            ////  bartender打印
            //this.bartenderPrint();
        }

        private void devReport打印(京配地址DTO 京配地址DTO)
        {
            this.快递打印信息DTOs.Add(
                new 快递打印信息DTO(
                    this.textBox收货地址.Text.Trim(), formarea, this.textBox姓名.Text.Trim(), this.textBox姓名.Text, this.textBox电话.Text, textBox6.Text, textBox6.Text
                    , 京配地址DTO
                    )                
                );
            //Report快递 report = new Report快递();
            Reportxxxx report = new Reportxxxx();
            report.DataSource = this.快递打印信息DTOs;


            // 显示预览
            ReportPrintTool tool = new ReportPrintTool(report);
            //tool.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("8.5x13", 100, 113);
            tool.ShowPreview();
            //tool.Print();
        }

        //private void Report_printProgress(object sender, PrintProgressEventArgs e)
        //{
        //    if (e.PageIndex == 1)
        //        e.PageSettings.Landscape = true;
        //}

        //private void PrintingSystem_StartPrint(object sender, PrintDocumentEventArgs e)
        //{ // Set the page range.
        //    e.PrintDocument.PrinterSettings.PrintRange = PrintRange.CurrentPage;
        //    e.PrintDocument.PrinterSettings.FromPage = 1; 
        //    e.PrintDocument.PrinterSettings.ToPage = 1; 
        //} 

            private void 瞎鸡巴打印() {
            var printDocument = new PrintDocument();
            //指定打印机
            printDocument.PrinterSettings.PrinterName = "Microsoft XPS Document Writer";
            //设置页边距
            printDocument.PrinterSettings.DefaultPageSettings.Margins.Left = 0;
            printDocument.PrinterSettings.DefaultPageSettings.Margins.Top = 0;
            printDocument.PrinterSettings.DefaultPageSettings.Margins.Right = 0;
            printDocument.PrinterSettings.DefaultPageSettings.Margins.Bottom = 0;
            //设置尺寸大小，如不设置默认是A4纸
            //A4纸的尺寸是210mm×297mm，
            //当你设定的分辨率是72像素/英寸时，A4纸的尺寸的图像的像素是595×842
            //当你设定的分辨率是150像素/英寸时，A4纸的尺寸的图像的像素是1240×1754
            //当你设定的分辨率是300像素/英寸时，A4纸的尺寸的图像的像素是2479×3508，
            printDocument.DefaultPageSettings.PaperSize = new PaperSize("A4", 595, 842);

            printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
            try
            {
                printDocument.Print();
            }
            catch (InvalidPrinterException)
            {

            }
            finally
            {
                printDocument.Dispose();
            }
        }
        void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            Font titleFont = new Font("黑体", 11, System.Drawing.FontStyle.Bold);//标题字体           
            Font fntTxt = new Font("宋体", 10, System.Drawing.FontStyle.Regular);//正文文字         
            Font fntTxt1 = new Font("宋体", 8, System.Drawing.FontStyle.Regular);//正文文字           
            System.Drawing.Brush brush = new SolidBrush(System.Drawing.Color.Black);//画刷           
            System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Black);           //线条颜色         

            try
            {
                //  这部分要改内容和坐标，bartender里面是拖拽的，这他妈对着bartender里面像素对着写吧
                e.Graphics.DrawString("标题name", titleFont, brush, new System.Drawing.Point(20, 10));
                e.Graphics.DrawString("资产编号：", fntTxt, brush, new System.Drawing.Point(20, 31));
                e.Graphics.DrawString("123456789123465", fntTxt, brush, new System.Drawing.Point(80, 31));
                e.Graphics.DrawString("资产序号：", fntTxt, brush, new System.Drawing.Point(20, 46));
                e.Graphics.DrawString("123456789131321", fntTxt, brush, new System.Drawing.Point(80, 46));
                e.Graphics.DrawString("底部name", fntTxt1, brush, new System.Drawing.Point(100, 62));

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }

            //如果打印还有下一页，将HasMorePages值置为true;
            e.HasMorePages = false;
        }
      
        private void button2_Click(object sender, EventArgs e)
        {

            string updatesql = "UPDATE a_bar_code_p \n" +
                 "SET QR_OTHER28 = '" + this.省.Text + "',\n" +
                 "QR_OTHER29 = '" + this.市.Text + "',\n" +
                 "QR_OTHER30 = '" + this.县.Text + "',\n" +
                 "QR_OTHER31 = '" + this.详细地址.Text + "' \n" +
                 "WHERE\n" +
                 "	QR_OTHER14 = '" + this.code.Text + "';";

            SQLerp.ExecuteSql(updatesql);
           
            return ;
        }

        private void label10_Click(object sender, EventArgs e)
        {

        }

        private void code_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                DataRow dataRow = new 快递Service().get修改信息(this.code.Text);

                //this.code.Text = dataRow["QR_NAME"].ToString();
                this.name.Text = dataRow["QR_OTHER26"].ToString();
                this.电话.Text = dataRow["QR_OTHER27"].ToString();
                this.省.Text = dataRow["QR_OTHER28"].ToString();
                this.市.Text = dataRow["QR_OTHER29"].ToString();
                this.县.Text = dataRow["QR_OTHER30"].ToString();
                this.详细地址.Text = dataRow["QR_OTHER31"].ToString();


            }
        }

        private void textBox生产号_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                try
                {
                    String json = RestCall.PostHttp("http://192.168.3.33:8090/sf/sfExpressOrder", this.textBox生产号.Text.Trim());
                    this.sfExpressMessageResult = FunctionHelper.JsonDeserialization<SfExpressMessageResult>(json);
                    if (sfExpressMessageResult.errorCode.Contains("200"))
                    {
                        this.orderReqContactInfo = FunctionHelper.JsonDeserialization<orderReqContactInfo>(sfExpressMessageResult.orderReqContactInfo);
                        PictureService.DownloadPicture("http://192.168.3.33:4545/sfexpress/" + this.textBox生产号.Text.Trim() + ".jpg", @"pic\" + this.textBox生产号.Text.Trim() + ".jpg", -1);
                        //pictureBox顺丰贴.Load(@"pic\" + this.textBox生产号.Text.Trim() + ".jpg");
                        System.Diagnostics.Process.Start(@"pic\" + this.textBox生产号.Text.Trim() + ".jpg");
                        this.顺丰日志();
                    }
                    else
                    {
                        MessageBox.Show(sfExpressMessageResult.errorMessage);
                        this.textBox生产号.Clear();
                        return;
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void simpleButton顺丰打印_Click(object sender, EventArgs e)
        {
            //PrintDialog MyPrintDg = new PrintDialog();
            //MyPrintDg.Document = printDocument1;
            //if (MyPrintDg.ShowDialog() == DialogResult.OK)
            //{
            //    try
            //    {
            //        printDocument1.Print();
            //    }
            //    catch
            //    {   //停止打印
            //        printDocument1.PrintController.OnEndPrint(printDocument1, new System.Drawing.Printing.PrintEventArgs());
            //    }
            //}
        }

        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(pictureBox顺丰贴.Image, 0, 0);
        }

        public XtraForm运单打印 顺丰口()
        {
            this.xtraTabPage京东打印.PageVisible = false;
            this.xtraTabPage京东修改地址.PageVisible = false;
            return this;
        }
        public XtraForm运单打印 京东口()
        {
            this.xtraTabPage顺丰打印.PageVisible = false;
            return this;
        }


        private void 顺丰日志()
        {
            String instertsql = "INSERT INTO `fragsmart-mtm`.`a_yundanxinxi` ( `name`, `waybill_number`, `phone`, `code`, `address`, `printingTime` )\n" +
"VALUES\n" +
"	( '" + orderReqContactInfo.contact + "'," +
" '" + this.sfExpressMessageResult.sfExpressNo + "'," +
" '" + orderReqContactInfo.mobile + "'," +
" 'KA.D" + this.textBox生产号.Text.Trim() + "'," +
" '" + this.orderReqContactInfo.getAddress() + "'," +
" '" + System.DateTime.Now.ToString() + "' );";
            SQLmtm.ExecuteSql(instertsql);
        }

        private void XtraForm运单打印_Activated(object sender, EventArgs e)
        {
            this.textBox生产号.Focus();
        }

        private void XtraForm运单打印_Load(object sender, EventArgs e)
        {
            if (this.@enum == 发货类型.顺丰)
            {
                this.textBox生产号.Focus();
            }
            else if (this.@enum == 发货类型.京东)
            {
                this.textEdit1.Focus();
            }
        }
    }

    public class 快递打印信息DTO {
        public String customerInformation { get; set; }
        public String area { get; set; }
        public String customer { get; set; }
        public String kehu { get; set; }
        public String phone { get; set; }
        public String yun_dan_hao { get; set; }
        public String yundanhao { get; set; }

        #region 京配地址DTO
        public String sourcetSortCenterId { get; set; } //	820864	始发分拣中心编码
        public String sourcetSortCenterName { get; set; } // 东莞亚一分拣中心    始发分拣中心名称
        public String targetSortCenterName { get; set; } //  兰州分拨中心 目的分拣中心名称
        public String road { get; set; } //	99E	始发道口号
        public String siteName { get; set; } //	◆  兰州兰工坪营业部 目的站点名称
        public String destinationTabletrolleyCode { get; set; } //	58176	目的分拣中心编码
        #endregion


        public 快递打印信息DTO(String customerInformation, String area, String customer, String kehu, String phone, String yun_dan_hao, String yundanhao, 京配地址DTO 京配地址DTO) {
            this.customerInformation = customerInformation;//地址
            this.area = area;
            this.customer = customer;//姓名
            this.kehu = kehu;//客户名
            this.phone = phone;//电话
            this.yun_dan_hao = yun_dan_hao;//运单号
            this.yundanhao = yundanhao+ "-1-1-";


            this.sourcetSortCenterId = 京配地址DTO.sourcetSortCenterId;
            this.sourcetSortCenterName = 京配地址DTO.sourcetSortCenterName;
            this.targetSortCenterName = 京配地址DTO.targetSortCenterName;
            this.road = 京配地址DTO.road;
            this.siteName = 京配地址DTO.siteName;
            this.destinationTabletrolleyCode = 京配地址DTO.destinationTabletrolleyCode;
        }
    }


    public class SfExpressMessageResult
    {
        public String errorCode { get; set; }
        public String errorMessage { get; set; }
        public String sfExpressNo { get; set; }
        public String orderReqContactInfo { get; set; }
    }
    public class orderReqContactInfo
    {
        public String address { get; set; }//详细地址
        public String city { get; set; }//城市
        public String company { get; set; }//公司
        public String contact { get; set; }//联系人
        public int contactType { get; set; }//类型1是寄件2是收件
        public String country { get; set; }//县
        public String mobile { get; set; }//手机
        public String province { get; set; }//省
        public String postCode { get; set; }//邮编
        public String tel { get; set; }

        public orderReqContactInfo()
        {

        }

        public String getAddress()
        {
            return this.province + this.city + this.country + this.address;
        }
    }
}